import create from '../../../utils/create2.js'
import store from '../../../store/index.js'
import { trim} from '../../../utils/util.js'
import SessionUtil, {JxbHttpClient} from '../../../data/session/session.js';
const Common = require('../../../utils/common.js');
create(store, {
  data: {
    numbers: 0,
    please: '请选择',
    numbers_tatas: false,
    times: 0,
    mark: '',
    name: '',
    date: '',
    time: '',
    canclick: 1,
    roomList: [],
    room: {},
    tasting: {},
    dinnerList: [],
    drinfo: {},
    couponLen: 0,
    coupon: {},
    fromCoupon: false,
    isPJH: false //品签会标识
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    getApp().getSaleMode()
    let { from, isCoupon } = options
    this.getUserInfo()
    //获取组件实例
    this.room = this.selectComponent('#room')
    this.dinner = this.selectComponent('#dinner')
    if (from && from === 'pjh') {
      wx.setNavigationBarColor({
        frontColor: '#000000',
        backgroundColor: '#ffffff',
      })
      wx.setNavigationBarTitle({
        title: '品鉴会信息',
      })
      const { tasting } = this.store.data
      const { dinner_room } = tasting
      this.setData({
        isPJH: true,
        dinnerList: dinner_room
      })
    } else {
      const { id } = options;
      this.setData({
        dinnerId: id,
        fromCoupon: isCoupon
      })
      // 获取餐厅信息
      this.getDinnerRoomInfo(id);
      // 设置时间范围
      this.item();
      // 获取最近一次
      this.getLastBookInfo();
      //寻找顾问信息
      this.getInfor();
      //查询包间列表
      this.getRoomList()
      //查询品签券
      if (this.data.fromCoupon === 'false' || !this.data.fromCoupon) { 
        this.getCoupon()
        }
    }
  },
  /**
  * @description:查询品鉴券记录 
  * @param {type} 
  * @return: 
   */
  getCoupon() {
    const { dinnerId } = this.data
    new JxbHttpClient().request({
      url: 'AppMaster/BookDinner/my_dinner_coupon_list',
      data: {
        dr_id: dinnerId
      },
    }).then(res => {
      const { result, data } = res._data
        if (result * 1 === 0) {
          this.setData({
            couponLen: data.count
          })
        }
    })
  },
  /**
  * @description: 获取包间
  * @param {type} 
  * @return: 
   */
  getRoomList() {
    const { dinnerId } = this.data
    new JxbHttpClient().request({
      url: 'AppMaster/DinnerRoom/dinnerCompartmentList',
      data: {
        dr_id: dinnerId
      },
    }).then(res => {
      const { result, data } = res._data
        if (result * 1 === 0) {
          this.store.data.roomList = data
          this.update()
        }
    })
  },
  numbers_top: function () {
    this.setData({
      numbers_tatas: !this.data.numbers_tatas,
    });
  },
  call: function (e) {
    var phone = e.currentTarget.id;
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  updatemark: function (e) {
    this.setData({
      mark: e.detail.value
    })
  },
  updatename: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  updamobile: function (e) {
    this.setData({
      mobile: e.detail.value
    })
  },

  getUserInfo() {
    SessionUtil.getInstance().then(session => {
      return session.getTheSessionUser()
    }).then(sessionUser => {
      this.setData({
        name: sessionUser.realName?sessionUser.realName:null,
        mobile: sessionUser.phoneNumber.length === 0 ? null : sessionUser.phoneNumber
      })
    })
  },
  submit() {
    var page = this;
    var name = page.data.name;
    var mobile = page.data.mobile;
    var phonetest = /^0?1\d{10}$/;
    const { room, dinner, coupon, tasting } = this.store.data
    const { isPJH } = this.data
    if (isPJH) {
      if (!dinner.dr_id) {
        Common.Alert('提示', '请选择餐厅！');
        return false;
      }
    } else {
      if (!tasting.book_dinner_theme || trim(tasting.book_dinner_theme).length === 0) {
        Common.Alert('提示', '请输入聚餐主题！');
        return false;
      }
    }
    if (!room.id) {
      Common.Alert('提示', '请选择包间！');
      return false;
    }
    if (!name) {
      Common.Alert('提示', '请输入您的姓名！');
      return false;
    }
    if (!mobile) {
      Common.Alert('提示', '请输入您的手机号！');
      return false;
    } else if (!phonetest.test(mobile)) {
      Common.Alert('提示', '请输入正确的手机号码');
      return false;
    }
  
    if (page.data.canclick === 1) {
      page.setData({
        canclick: 0
      })
      const { isPJH } = this.data
      if (isPJH) { //品签会
        Common.my_request({
          url: '/AppMaster/BookDinner/accountJudgeAdd',
          data: {
            dinner_coupon_code: this.data.tasting.dinner_coupon_code,
            book_time: `${room.date} ${room.type}`,
            dr_id: dinner.dr_id,
            compartment_id: room.id,
            people_num: this.data.tasting.min_people_num,
            name: page.data.name,
            mobile: page.data.mobile,
            mark: page.data.mark
          },
          method: 'post',
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success: res => {
            if (res.data.result == 0) {
              console.log(res.data.data)
              wx.showToast({
                title: res.data.message,
                icon: 'success',
                duration: 2000,
                success: () => {
                  this.store.data.room = {}
                  this.update()
                  wx.navigateTo({
                    url: '/pages/index/foodsuccess/index?title=' + page.data.title + '&bookid=' + res.data.data.book_dinner_id + '&from=PJH',
                  })
                }
              })
            } else {
              wx.showToast({
                title: res.data.message,
                image: '../../imges/fail.png',
                duration: 2000
              })
            }
          },
          complete: function (res) {
            setTimeout(function () {
              page.setData({
                canclick: 1
              })
            }, 1000);
          }
        })
      } else {
        Common.my_request({
          url: '/AppMaster/BookDinner/bookDinner',
          data: {
            number: page.data.tasting.min_people_num,
            name: page.data.name,
            mobile: page.data.mobile,
            book_time: `${room.date} ${room.type}`,
            compartment_id: room.id,
            shop_name: dinner.name,
            dr_id: dinner.dr_id,
            mark: page.data.mark,
            book_dinner_theme: tasting.book_dinner_theme,
            dinner_coupon_id: coupon.dinner_coupon_id
          },
          method: 'post',
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success: res => {
            if (res.data.result == 0) {
              wx.showToast({
                title: res.data.message,
                icon: 'success',
                duration: 2000,
                success: () => {
                  this.store.data.room = {}
                  this.store.data.coupon = {}
                  this.update()
                }
              })
              setTimeout(function () {
                wx.redirectTo({
                  url: '/pages/index/foodsuccess/index?title=' + page.data.title + '&bookid=' + res.data.data,
                })
              }, 1000);
            } else {
              wx.showToast({
                title: res.data.message,
                image: '../../imges/fail.png',
                duration: 2000
              })
            }
          },
          complete: function (res) {
            setTimeout(function () {
              page.setData({
                canclick: 1
              })
            }, 1000);
          }
        })
      }
    } else {
      return false;
    }
  },
  /**
   * 获取最近一次
   */
  getLastBookInfo: function () {
    var page = this
    Common.my_request({
      url: '/AppMaster/BookDinner/getLastBookInfo',
      success: function (res) {
        if (res.data.result == 0) {
          page.setData({
            BookInfo: res.data.data
          })
        } else {
        }
      }
    })
  },
  /**
   * 获取餐厅详细信息
   */
  getDinnerRoomInfo: function (id) {
    var page = this
    Common.my_request({
      url: '/AppMaster/BookDinner/getDinnerRoomInfo',
      data: {
        dr_id: id
      },
      success: function (res) {
        if (res.data.result == 0) {
          page.setData({
            drinfo: res.data.data
          })
        } else {
        }
      }
    })
  },
  /**
     * 获取顾问信息
     */
  getInfor: function () {
    SessionUtil.getInstance().then(session => {
      let server = session.getTheSellingServerSync(), vCard = server.getTheVCardSync()
      this.setData({
        salesmanVCard : {
          avatarUri:vCard.avatarUri,
          showName: vCard.name,
          contactPhone: vCard.contactPhone
        }
      })
    })
  },
  numbers_list: function (e) {
    var data = e.currentTarget.id.split("_");
    this.setData({
      numbers: data[0],
      numbers_tata: data[1],
    });
    this.numbers_top()
  },
  item: function () {
    var myDate = new Date();
    var Hours = myDate.getHours() + 2;
    var today = this.getdatastr(0)
    // var after = this.getdatastr(2)
    if (Hours > 23) {
      Hours = Hours - 24;
      today = this.getdatastr(1)
      // after = this.getdatastr(3)
    }
    var min = myDate.getMinutes();
    if (min.toString().length == 1) {
      min = "0" + min;
    }
    var start = Hours + ':' + min;
    this.setData({
      time: start,//开始时间
      start: start,//开始时间
      date: today,//开始日期
      //after: after,//结束日期
    });

  },
  bindTimeChange: function (e) {
    this.setData({
      time: e.detail.value
    })
  },
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
    var myDate = new Date();
    var a = myDate.toLocaleDateString().split("/")[2],
      b = this.data.date.split("-")[2];
    var Hours = myDate.getHours() + 2;
    var start = Hours + ':' + myDate.getMinutes();
    if (a == b) {
      this.setData({
        start: start,//开始时间
      });
    } else {
      this.setData({
        start: '6:00',//开始时间
      });
    }
  },
  getdatastr: function (AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期 
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1;//获取当前月份的日期 
    var d = dd.getDate();
    return y + "-" + m + "-" + d;
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },
  //选择包间 
  chooseRoom() {
    const { drinfo } = this.data
    const { dr_id } = drinfo
    if (!dr_id) {
      Common.Alert("提示", "请先选择餐厅!");
      return
    }
    wx.setNavigationBarTitle({
      title: this.store.data.dinner.name
    })
    this.room.showRoom()
  },
  selectDinner() {
    const { isPJH } = this.data
    if (!isPJH) return
    this.dinner.show()
  },
  confirmDinner() {
    this.dinner.hide()
    const { dinner } = this.store.data
    this.setData({
      drinfo: dinner,
      dinnerId: dinner.dr_id
    })
    this.getRoomList()
  },
  numberInput(e) {
    const { value } = e.detail
    this.store.data.tasting.min_people_num = value
    this.update()
  },
  subjectInput(e) {
    const { value } = e.detail
    this.store.data.tasting.book_dinner_theme = value
    this.update()
  },
  selectCoupon(e) {
    const { fromCoupon, dinnerId} = this.data
    if (fromCoupon && fromCoupon!=='false') return
    const { couponLen } = this.data
    if (couponLen * 1 === 0) {
      Common.Alert('提示', '暂无可用品鉴券')
      return
    }
    wx.navigateTo({
      url: `/subPage/tastingCoupon/index?dinnerId=${dinnerId}`,
    })
  }
})